﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc;

namespace Topro.Admin.Controllers
{
    using Topro.Application.Interface;

    using Topro.Entity;
    using Topro.Entity.Enum;
    using Topro.Entity.Query;
    using Topro.Entity.Request.Menu;
    using Topro.Entity.Request.Permission;
    using Topro.Entity.Request.Role;
    using Topro.Entity.Request.User;
    using Topro.Entity.Response.Menu;
    using Topro.Entity.Response.Permission;
    using Topro.Entity.Response.Role;

    /// <summary>
    /// 权限控制器
    /// </summary>
    public class AuthController : BaseController
    {
        #region 注入
        /// <summary>
        /// 权限接口
        /// </summary>
        private readonly AuthService _authService;

        /// <summary>
        /// 日志接口
        /// </summary>
        private readonly LogService _logService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="authService">权限接口</param>
        /// <param name="logService">日志接口</param>
        public AuthController(LoginService loginService,AuthService authService, LogService logService)
        {
            _authService = authService;
            _logService = logService;
        }
        #endregion

        #region 用户
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [AuthFilter(AuthCode.User0001)]
        public new IActionResult User()
        {
            return View("User");
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<UserResponse></returns>
        [AuthFilter(AuthCode.User0001)]
        public IActionResult UserQuery(UserQuery query)
        {
            var list = _authService.GetUserPager(query);

            return PartialView("_UserQuery", list);
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="id">权限编号</param>
        /// <returns></returns>
        [AuthFilter(AuthCode.User0002, AuthCode.User0003)]
        public IActionResult UserAddOrEdit(int? id)
        {
            var viewName = "UserEdit";

            var model = _authService.GetUser(id);

            if (id.HasValue)
            {
                viewName = "UserEdit";
            }

            return View(viewName, model);
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="request">角色</param>
        /// <param name="ids">角色编号</param>
        /// <returns></returns>
        [AuthFilter(AuthCode.User0002, AuthCode.User0003)]
        [HttpPost]
        public JsonResult SaveUser(SaveUserRequest request, List<int> ids)
        {
            request.Ip = Ip;
            request.UserId = UserId;

            var response = _authService.SaveUser(request, ids);

            return Json(response);
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id">编号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        [HttpPost]
        [AuthFilter(AuthCode.User0004)]
        public JsonResult UpdateUserStatus(int id, sbyte status)
        {
            var response = new JResult()
            {
                Success = false
            };

            response = _authService.UpdateUserStatus(id, status);

            return Json(response);
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id">编号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        [HttpPost]
        [AuthFilter(AuthCode.User0004)]
        public IActionResult GoogleVerify(int id, sbyte status)
        {
            var response = new JResult()
            {
                Success = false
            };

            response = _authService.GoogleVerify(id, status);

            return Json(response);
        }

        #endregion

        #region 角色
        /// <summary>
        /// 首页
        /// </summary>
        /// <returns>视图</returns>
        [AuthFilter(AuthCode.Role0001)]
        public IActionResult Role()
        {
            return View("Role");
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<PermissionResponse></returns>
        [AuthFilter(AuthCode.Role0001)]
        public IActionResult RoleQuery(RoleQuery query)
        {
            var list = _authService.GetRolePager(query);

            return PartialView("_RoleQuery", list);
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="id">权限编号</param>
        /// <returns></returns>
        [AuthFilter(AuthCode.Role0002, AuthCode.Role0002)]
        public IActionResult RoleAddOrEdit(int? id)
        {
            var model = new RoleResponse();

            var viewName = "RoleEdit";

            if (id.HasValue)
            {
                model = _authService.GetRole(id.Value);
            }

            return View(viewName, model);
        }

        /// <summary>
        /// 角色[新增、编辑]
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AuthFilter(AuthCode.Role0002, AuthCode.Role0002)]
        public JsonResult SaveRole(SaveRoleRequest request, List<SelectedAuth> selectedAuth)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                #region 验证
                if (string.IsNullOrEmpty(request.Name))
                {
                    throw new Exception("角色名称为空.");
                }

                var status = new List<int>()
                {
                    (int)RoleStatus.启用,
                    (int)RoleStatus.禁用
                };

                if (!request.Status.HasValue)
                {
                    throw new Exception("选择状态.");
                }

                if (!status.Contains(request.Status.Value))
                {
                    throw new Exception("参数错误.");
                }
                #endregion

                request.Ip = Ip;
                request.UserId = UserId;

                response = _authService.SaveRole(request, selectedAuth);
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }


            return Json(response);
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id">编号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        [HttpPost]
        [AuthFilter(AuthCode.Role0004)]
        public JsonResult UpdateRoleStatus(int id, sbyte status)
        {
            var response = new JResult()
            {
                Success = false
            };

            response = _authService.UpdateRoleStatus(id, status);

            return Json(response);
        }

        /// <summary>
        /// 获取角色菜单权限树
        /// </summary>
        /// <param name="RoleId">角色编号</param>
        /// <returns>角色菜单权限树列表</returns>
        [AuthFilter(AuthCode.Role0002, AuthCode.Role0002)]
        public JsonResult GetZTree(ZTreeRequest request)
        {
            request.UserPermission = UserPermissions;
            var response = _authService.GetZTree(request);

            return Json(response);
        }
        #endregion
        
        #region 权限
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [AuthFilter(AuthCode.Permission0001)]
        public IActionResult Permission()
        {
            return View();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<PermissionResponse></returns>
        [AuthFilter(AuthCode.Permission0001)]
        public IActionResult PermissionQuery(PermissionQuery query)
        {
            var list = _authService.GetPermissionPager(query);

            return PartialView("_PermissionQuery", list);
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="id">权限编号</param>
        /// <returns></returns>
        [AuthFilter(AuthCode.Permission0002, AuthCode.Permission0003)]
        public IActionResult PermissionAddOrEdit(int? id)
        {
            var model = new PermissionResponse();
            if (id.HasValue)
            {
                model = _authService.GetPermission(id.Value);
            }

            return View("PermissionEdit", model);
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <returns></returns>
        [AuthFilter(AuthCode.Permission0002, AuthCode.Permission0003)]
        public JsonResult SavePermission(SavePermissionRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                # region 验证
                //名称
                if (string.IsNullOrEmpty(request.Name))
                {
                    throw new Exception("权限名称不能为空.");
                }

                var nameReg = new Regex(@"^.{2,40}$");
                if (!nameReg.IsMatch(request.Name))
                {
                    throw new Exception("权限名称必须介于 2 和 40 之间");
                }
                //代码
                if (string.IsNullOrEmpty(request.Code))
                {
                    throw new Exception("权限代码不能为空.");
                }

                var codeReg = new Regex(@"^.{2,40}$");
                if (!codeReg.IsMatch(request.Code))
                {
                    throw new Exception("权限代码必须介于 2 和 40 之间");
                }
                //排序
                if (string.IsNullOrEmpty(request.DisplayOrder))
                {
                    throw new Exception("排序不能为空.");
                }

                var sortNoReg = new Regex(@"^(([1-9]\d{0,1})|0)?$");
                if (!sortNoReg.IsMatch(request.DisplayOrder))
                {
                    throw new Exception("排序只能输入两位正整数.");
                }
                //状态
                if (!request.Status.HasValue)
                {
                    throw new Exception("选择状态.");
                }

                var status = new List<int>()
                {
                    (int)PermissionStatus.启用,
                    (int)PermissionStatus.禁用
                };

                if (!status.Contains(request.Status.Value))
                {
                    throw new Exception("状态参数错误.");
                }
                #endregion

                request.Ip = Ip;
                request.UserId = UserId;

                response = _authService.SavePermission(request);
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return Json(response);
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id">编号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        [HttpPost]
        [AuthFilter(AuthCode.Permission0004)]
        public JsonResult UpdatePermissionStatus(int id, sbyte status)
        {
            var response = new JResult()
            {
                Success = false
            };

            response = _authService.UpdatePermissionStatus(id, status);

            return Json(response);
        }
        #endregion

        #region 菜单
        /// <summary>
        /// 菜单首页
        /// </summary>
        /// <returns>视图</returns>
        [AuthFilter(AuthCode.Menu0001)]
        public IActionResult Menu()
        {
            return View("Menu");
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<MenuResponse></returns>
        [AuthFilter(AuthCode.Menu0001)]
        public IActionResult MenuQuery(MenuQuery query)
        {
            var list = _authService.GetMenuPager(query);

            return PartialView("_MenuQuery", list);
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        [AuthFilter(AuthCode.Menu0002, AuthCode.Menu0003)]
        public IActionResult MenuAddOrEdit(int? id)
        {
            var model = new MenuResponse();
            if (id.HasValue)
            {
                model = _authService.GetMenu(id.Value);

            }
            else
            {
                model.IsNav = (int)IsNav.显示;
                model.Status = (int)MenuStatus.启用;
            }

            ViewBag.menuFirst = _authService.GetMenuFirst();

            return View("MenuEdit", model);
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [AuthFilter(AuthCode.Menu0002, AuthCode.Menu0003)]
        public JsonResult SaveMenu(SaveMenuRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                # region 验证
                //根目录
                if(request.Id<=0)
                {
                    if (!request.ParentId.HasValue)
                    {
                        throw new Exception("菜单根目录不能为空.");
                    }
                }
                //名称
                if (string.IsNullOrEmpty(request.Name))
                {
                    throw new Exception("菜单名称不能为空.");
                }

                var nameReg = new Regex(@"^.{2,40}$");
                if (!nameReg.IsMatch(request.Name))
                {
                    throw new Exception("菜单名称必须介于 2 和 40 之间");
                }
                //状态
                if (!request.IsNav.HasValue)
                {
                    throw new Exception("选择导航显示.");
                }

                var isVav = new List<int>()
                {
                    (int)IsNav.显示,
                    (int)IsNav.不显示
                };

                if (!isVav.Contains(request.IsNav.Value))
                {
                    throw new Exception("参数错误.");
                }
                //菜单地址
                if (!string.IsNullOrEmpty(request.Url))
                {
                    var codeReg = new Regex(@"^.{0,120}$");
                    if (!codeReg.IsMatch(request.Url))
                    {
                        throw new Exception("权限代码必须介于 2 和 40 之间");
                    }
                }
                //排序
                if (string.IsNullOrEmpty(request.DisplayOrder))
                {
                    throw new Exception("排序不能为空.");
                }

                var sortNoReg = new Regex(@"^(([1-9]\d{0,1})|0)?$");
                if (!sortNoReg.IsMatch(request.DisplayOrder))
                {
                    throw new Exception("排序只能输入两位正整数.");
                }
                //状态
                if (!request.Status.HasValue)
                {
                    throw new Exception("选择状态.");
                }

                var status = new List<int>()
                {
                    (int)MenuStatus.启用,
                    (int)MenuStatus.禁用
                };

                if (!status.Contains(request.Status.Value))
                {
                    throw new Exception("参数错误.");
                }
                #endregion

                request.Ip = Ip;
                request.UserId = UserId;

                response = _authService.SaveMenu(request);
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return Json(response);
        }
        #endregion

        #region 菜单权限
        /// <summary>
        /// 子菜单
        /// </summary>
        /// <returns>视图</returns>
        [AuthFilter(AuthCode.Menu0002, AuthCode.Menu0003)]
        public IActionResult MenuPermission(int ParentId)
        {
            ViewBag.ParentId = ParentId;

            return View("MenuPermission");
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<PermissionResponse></returns>
        [HttpGet]
        [AuthFilter(AuthCode.Menu0002, AuthCode.Menu0003)]
        public IActionResult MenuPermissionQuery(PermissionQuery query)
        {
            var list = _authService.GetMenuPermissionPager(query);

            return PartialView("_MenuPermissionQuery", list);
        }
        #endregion

        #region 子菜单
        /// <summary>
        /// 子菜单
        /// </summary>
        /// <returns>视图</returns>
        public IActionResult ChildMenu(int ParentId)
        {
            ViewBag.ParentId = ParentId;

            return View("ChildMenu");
        }

        /// <summary>
        /// 子菜单查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<PermissionResponse></returns>
        public IActionResult ChildMenuQuery(MenuQuery query)
        {
            var list = _authService.GetMenuPager(query);

            return PartialView("_ChildMenuQuery", list);
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public IActionResult ChildMenuAdd(int parentId)
        {
            var model = new MenuResponse();
            model.ParentId = parentId;
            model.IsNav = (int)IsNav.显示;
            model.Status = (int)MenuStatus.启用;
            return View("ChildMenuEdit", model);
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public IActionResult ChildMenuAddOrEdit(int? id, int parentId)
        {
            var model = new MenuResponse();
            if (id.HasValue)
            {
                model = _authService.GetMenu(id.Value);
                model.PermissionResponse = _authService.GetMenuPermission(id.Value);
            }
            else
            {
                model.ParentId = parentId;
                model.IsNav = (int)IsNav.显示;
                model.Status = (int)MenuStatus.启用;
            }

            return View("ChildMenuEdit", model);
        }
        #endregion

        #region 日志
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [AuthFilter(AuthCode.Log0001)]
        public IActionResult Log()
        {
            return View();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<PermissionResponse></returns>
        [AuthFilter(AuthCode.Log0001)]
        public IActionResult LogQuery(LogQuery query)
        {
            var list = _logService.GetPager(query);

            return PartialView("_LogQuery", list);
        }
        #endregion
    }
}
